﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;

namespace Silverlight3dApp.Learning.Lesson04
{
    public class EvadingSprite : AutomatedSprite
    {
        private readonly SpriteManager _spriteManager;

        private readonly int _evasionRange;
        private bool _evade;

        public EvadingSprite(Texture2D texture, Vector2 position, Vector2 frameSize, int collisionOffset, Vector2 currentFrame, Vector2 sheetSize, Vector2 speed, SoundEffect collisionSound, SpriteManager spriteManager, int evasionRange) : base(texture, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, collisionSound)
        {
            _spriteManager = spriteManager;
            _evasionRange = evasionRange;
        }

        public EvadingSprite(Texture2D texture, Vector2 position, Vector2 frameSize, int collisionOffset, Vector2 currentFrame, Vector2 sheetSize, Vector2 speed, SoundEffect collisionSound, int millisecondsPerFrame, SpriteManager spriteManager, int evasionRange) : base(texture, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, collisionSound, millisecondsPerFrame)
        {
            _spriteManager = spriteManager;
            _evasionRange = evasionRange;
        }

        public override Vector2 Direction
        {
            get
            {
                return _Speed;
            }
        }

        public override void Update(GameTime gameTime, Rectangle clientBounds)
        {
            base.Update(gameTime, clientBounds);

            var playerPosition = _spriteManager.PlayerPosition;
            var speed = Math.Max(_Speed.X, _Speed.Y);

            if (_evade)
            {
                if (_Position.X > playerPosition.X)
                {
                    _Position.X += speed;
                }
                else if (_Position.X < playerPosition.X)
                {
                    _Position.X -= speed;
                }

                if (_Position.Y > playerPosition.Y)
                {
                    _Position.Y += speed;
                }
                else if (_Position.Y < playerPosition.Y)
                {
                    _Position.Y -= speed;
                }
            }
            else
            {
                _evade = Vector2.Distance(_Position, playerPosition) < _evasionRange;
            }
        }
    }
}